var dataSource;
var dataSourceSchemas;
var start;
var end;
var entrenamiento;
var calif_min;
var dialog;
var attempts;
var sched = null;
var bandComm = false;
var tr_closed = false;
var grid = $("#grid");
var gridSchedules = $("#gridSchedules");
var countRows = 1;
var prevRow = null;

$('#entrenamientos').val("");

$(document).ready(function () {
    dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: appBosch.read,
                dataType: "json"
            },
            update: {
                url: appBosch.urlEvaluations,
                dataType: "json",
                type: 'POST'
            },
            destroy: {
                url: appBosch.crud.destroy,
                dataType: "json"
            },
            parameterMap: function (options, operation) {
                var params = {};
                switch (operation)
                {
                    case 'read':
                        break;
                    case 'update':
                        var models = [];
                        for (i = 0; i < options.models.length; i++) {
                            models.push({value: options.models[i].value, date_ap: options.models[i].date_ap, calif: options.models[i].calif});
                        }
                        params.models = kendo.stringify(models);
                        params.testId = entrenamiento;
                        params.scheduleId = sched;
                        break;
                    case 'destroy':
                        params.ids = [];
                        for (i = 0; i < options.models.length; i++) {
                            params.ids.push(options.models[i].value);
                        }
                        params.scheduleId = sched;
                        params.testId = entrenamiento;
                }
                return params;
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    userId: {
                        type: "string",
                        editable: false
                    },
                    text: {
                        type: "string",
                        editable: false
                    },
                    nomina: {
                        type: "string",
                        editable: false
                    },
                    reg_date: {
                        type: "date",
                        editable: false
                    },
                    att_ab: {
                        type: "number",
                        editable: false
                    },
                    max_calif: {
                        type: "string",
                        editable: false
                    },
                    calif: {
                        type: "number",
                        editable: true,
                        nullable: true,
                        validation: {
                            min: 0,
                            max: 100,
                            requiered: true
                        }
                    },
                    date_ap: {
                        type: "date",
                        editable: true,
                        nullable: true
                    },
                    band_calif: {
                        type: "number",
                        editable: false
                    }
                }
            }
        }
    });

    var today = kendo.date.today();

    start = $("#start").kendoDatePicker({
        value: today,
        change: getSchedulesByDates,
        parseFormats: ["MM/dd/yyyy"]
    }).data("kendoDatePicker");

    end = $("#end").kendoDatePicker({
        value: today,
        change: function () {
            endChange();
            getSchedulesByDates();
        },
        parseFormats: ["MM/dd/yyyy"]
    }).data("kendoDatePicker");

    $('#start').attr('readonly', 'readonly');
    $('#end').attr('readonly', 'readonly');

    start.min(new Date(2014, 0, 1));
    var d = new Date();
    d.setDate(d.getDate() - 7);
    start.value(d);
    start.max(today);
    end.min(start.value());
    end.value(today);

    grid.kendoGrid({
        toolbar: [
            {
                name: "save"
            },
            {
                name: "cancel"
            },
            {
                name: "excel"
            },
            {
                name: "pdf"
            },
            {
                name: "unscribe",
                template: '<a id="unscribeButton" class="k-button k-button-icontext k-grid-unscribe" href="\\\\#"><span class="fa fa-trash-o"></span>Vaciar curso</a>'
            }
        ],
        excel: {
            allPages: true,
            fileName: "Inscritos.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Inscritos.pdf"
        },
        autoBind: false,
        scrollable: false,
        filterable: {
            mode: "row",
            extra: false
        },
        selectable: true,
        navigatable: true,
        sortable: true,
        resizable: true,
        columnMenu: true,
        dataSource: dataSource,
        dataBound: function () {
            countRows = 1;
        },
        columns: [
            {title: "#", template: '#=countRows++#', width: 40},
            {
                field: "nomina",
                title: "Nómina",
                width: 160,
                filterable: {
                    cell: {
                        showOperators: false
                    }
                }

            },
            {
                field: "text",
                title: "Asociado",
                filterable: {
                    cell: {
                        showOperators: false,
                        operator: "contains"
                    }
                }

            },
            {
                field: "reg_date",
                title: "Fecha de registro",
                template: '<span title="#=kendo.toString(reg_date, "D")#" >#=kendo.toString(reg_date, "d")#</span>',
                width: 150,
                filterable: {
                    cell: {
                        showOperators: false
                    }
                }
            },
            {
                field: "att_ab",
                title: "Intentos disponibles",
                width: 120,
                filterable: {
                    cell: {
                        showOperators: false
                    }
                }
            },
            {
                field: "date_ap",
                title: "Fecha de aplicación",
                template: '# if (date_ap != null) { # <span title="#=kendo.toString(date_ap, "D")#" >#=kendo.toString(date_ap, "d")#</span> # } #',
                editor: editDate,
                width: 150,
                filterable: {
                    cell: {
                        showOperators: false
                    }
                }
            },
            {
                field: "calif",
                title: "Calificación",
                template: "#= calif != null ? calif : '' #",
                editor: editCalif,
                width: 120,
                filterable: {
                    cell: {
                        showOperators: false
                    }
                }
            },
            {
                command: [
                    {
                        name: "destroy",
                        text: ""
                    }
                ],
                title: "&nbsp;",
                width: 90
            }
        ],
        editable: {
            confirmation: "¿Estás seguro que deseas desinscribir a este asociado?",
            mode: "incell"
        }
    });
    grid.on('click', '#unscribeButton', unscribeAll);

    $('body').on('click', '#sendComment', function () {
        dialog.close();
    });

    dataSourceSchemas = new kendo.data.DataSource({
        transport: {
            read: {
                url: appBosch.urlSchedulesDates,
                dataType: "json"
            },
            parameterMap: function (options, operation) {
                var params = {};
                switch (operation)
                {
                    case 'read':
                        params = {
                            startD: kendo.toString(start.value(), "u"),
                            endD: kendo.toString(end.value(), "u"),
                            filterClosed: $('#closed-filter').is(":checked")
                        };
                        break;
                }
                return params;
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    text: {type: "string"},
                    room: {type: "string"},
                    start: {type: "date"},
                    capacity: {type: "string"},
                    registered: {type: "string"},
                    closed: {type: "boolean"},
                    min_cal: {type: 'string'},
                    attempts: {type: 'number'},
                    train: {type: 'string'}
                }
            }
        }
    });

    gridSchedules.kendoGrid({
        autoBind: false,
        scrollable: true,
        filterable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        selectable: "row",
        height: 200,
        dataSource: dataSourceSchemas,
        editable: 'inline',
        toolbar: ['excel', 'pdf'],
        excel: {
            allPages: true,
            fileName: "Cursos.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Cursos.pdf"
        },
        dataBound: function (data) {
            console.log(prevRow);
            if (prevRow != null && prevRow >= 0) {
                var selector = 'tr:eq(' + prevRow + ')';
                console.log(selector);
                gridSchedules.data('kendoGrid').select(selector);
            } else {
                var firstRow = gridSchedules.find('tr:eq(1)');
                if (firstRow.length > 0) {
                    gridSchedules.data('kendoGrid').select('tr:eq(1)');
                }
            }
            prevRow = null;
        },
        columns: [
            {
                field: "text",
                title: "Curso"
            },
            {
                field: "room",
                title: "Sala"
            },
            {
                field: "start",
                title: "Fecha",
                template: '<span title="#=kendo.toString(start, "F")#">#=kendo.toString(start, "g")#</span>'
            },
            {
                field: "capacity",
                title: "Capacidad",
                width: 100
            },
            {
                field: "registered",
                title: "Registrados",
                width: 100
            },
            {
                field: "closed",
                title: "Cerrado",
                width: 100,
                template: '# if (closed) { # <i class="fa fa-lock closed-icon"></i> # } else { # <span class="k-button close-course" >Cerrar</span> # } #'
            }
        ],
        change: function () {
            var hasChanges = dataSource.hasChanges();
            if (hasChanges === false || confirm('Vas a perder los cambios que no has guardado ¿Deseas continuar?') === true) {
                $('#detailCourse').removeClass('hidden');
                var selectedRows = this.select();
                var dataItem = this.dataItem(selectedRows[0]);
                var kendoGridUsers = $('#grid').data('kendoGrid');
                var regNewUsers = $('#regNewUsers');
                var toolbarButtons = $('.k-grid-save-changes, .k-grid-cancel-changes, .k-grid-unscribe');
                regNewUsers.show();
                toolbarButtons.show();
                kendoGridUsers.showColumn(7);
                if (dataItem.closed === true) {
                    regNewUsers.hide();
                    kendoGridUsers.hideColumn(7);
                    toolbarButtons.hide();
                }
                $('#courseName').html(dataItem.text);
                if (sched != dataItem.id) {
                    sched = dataItem.id;
                    entrenamiento = dataItem.train;
                    appBosch.fechaHora = new Date(dataItem.start);
                    calif_min = dataItem.min_cal;
                    attempts = dataItem.attempts;
                    tr_closed = dataItem.closed;
                    if (tr_closed == true) {
                        $('#regNomText').prop('disabled', true);
                        $("#regNomButt").off('click');
                    } else {
                        $('#regNomText').prop('disabled', false);
                        $("#regNomButt").off('click');
                        $("#regNomButt").on('click', regNom);
                    }
                    dataSource.transport.options.read.url = appBosch.read + '/' + sched;
                    dataSource.read();
                }
            }
            else{
                return false;
            }
        },
        remove: function (e) {
            if (e.model.closed) {
                kendoAlert('Este curso ya fue cancelado', 'Cancelacion de cursos');
                e.sender.cancelChanges();
            }
        }
    });

    gridSchedules.on('click', '.close-course', closeCourse);
    $("#regNomButt").on('click', regNom);
    $('#closed-filter').on('change', getSchedulesByDates);


    getSchedulesByDates();
});

function unscribeAll(e) {
    e.preventDefault();
    if (checkChanges() && confirm('¿Estás seguro que deseas eliminar todos los asociados inscritos en este curso?') === true) {
        var button = $('#unscribeButton');
        grid.off('click', '#unscribeButton');
        button.html('<span class="fa fa-spin fa-spinner" ></span>');
        $.get(appBosch.urlUnscribe + '/' + sched + '/' + entrenamiento, {}, function () {
            button.html('<span class="fa fa-trash-o"></span>Vaciar curso');
            grid.on('click', '#unscribeButton', unscribeAll);
            dataSource.read();
            dataSourceSchemas.read();
        });
    }
}

function regNom() {
    if (sched === null) {
        kendoAlert('Debe de seleccionar un curso', 'Registro de asociados');
        return;
    }
    $("#regNomButt").addClass('hidden');
    $('#wait').removeClass('hidden');
    prevRow = gridSchedules.find('tr.k-state-selected').index();
    prevRow++;
    $.get(appBosch.registerAss, {userIds: $('#regNomText').val(), scheduleId: sched}, function (res) {
        if (res != '') {
            if (res != false) {
                kendoAlertTable(res);
            } else {
                kendoAlert('No se selecciono ningun curso al cual inscribir o no se introdujo ningun usuario', 'Registro de asociados');
            }
        }
        $('#regNomText').val('');
        $('#wait').addClass('hidden');
        $("#regNomButt").removeClass('hidden');
        sched = null;
        dataSourceSchemas.read();
    });
}

function editCalif(container, options) {
    var input = $("<input/>");
    input.attr("name", options.field);
    input.appendTo(container);
    input = input.kendoNumericTextBox({
        max: 100,
        min: 0,
        value: 100,
        change: changeValCal,
        spin: changeValCal
    }).data('kendoNumericTextBox');
    if (tr_closed == true || (options.model.att_ab > 0 && options.model.band_calif != null)) {
        input.enable(false);
    }
}

function editDate(container, options) {
    var input = $("<input/>");
    input.attr("name", options.field);
    input.appendTo(container);
    input = input.kendoDatePicker({
        format: "yyyy/MM/dd",
        value: appBosch.fechaHora
    }).data('kendoDatePicker');
    if (tr_closed == true || (options.model.att_ab > 0 && options.model.band_calif != null)) {
        input.enable(false);
    }
}

function getSchedulesByDates() {
    sched = null;
    $('#detailCourse').addClass('hidden');
    dataSourceSchemas.read();
}

function endChange() {
    var endDate = end.value();
    if (endDate) {
        start.max(endDate);
    }
}

function setCalif(e) {
    var dataItem = $(e.currentTarget).closest("tr");
    dataItem = dataSource.getByUid(dataItem.data('uid'));
    var userId = dataItem.userId;
    var contentTemp = $("#windowTemplate").html();
    var temp = kendo.template(contentTemp);
    $.get(appBosch.urlUserAttempts + '/' + userId + '/' + entrenamiento, {}, function (res) {
        dialog = $('<div id="windowCalifAttempt" ></div>');
        var info = {utId: dataItem.id, userId: userId, testId: entrenamiento, res: res, min_cal: calif_min, attempts: attempts};
        dialog.html(temp(info));
        dialog.kendoWindow({
            title: "Calificaciones",
            minWidth: 400,
            open: function () {
                $('#windowCalifAttempt #valCalif').kendoNumericTextBox({
                    min: 0,
                    max: 100,
                    value: 100,
                    change: changeValCal,
                    spin: changeValCal
                });
                $('#windowCalifAttempt #valDate').kendoDatePicker({
                    format: "yyyy/MM/dd",
                    value: appBosch.fechaHora
                });
            },
            deactivate: function () {
                dialog.data("kendoWindow").destroy();
            }
        }).data("kendoWindow").open().center();
    });
}

function closeCourse(e) {
    var dataItem = $(e.currentTarget).closest("tr");
    dataItem = dataSourceSchemas.getByUid(dataItem.data('uid'));
    if (checkChanges() == true) {
        $.get(appBosch.cancelSchedule, {id: dataItem.value}, function (resp) {
            if (typeof (resp.res) != 'string') {
                var contentTemp = $("#windowComment").html();
                var temp = kendo.template(contentTemp);
                var combo;
                dialog = $('<div id="window" ></div>');
                dialog.html(temp({url: appBosch.urlCreateLogCancel + '/' + resp.res.id}));
                dialog = dialog.kendoWindow({
                    title: "Comentario",
                    minWidth: 400,
                    modal: true,
                    deactivate: function () {
                        $.get($('#sendComment').data('url'), {comment: combo.text() + ' - ' + $('#comment').val()}, function () {
                            dataSourceSchemas.read();
                            dataSource.read();
                        });
                        this.destroy();
                    },
                    open: function () {
                        combo = $('#comboComment').kendoDropDownList({
                            dataTextField: "text",
                            dataValueField: "value",
                            dataSource: {
                                data: [
                                    {value: 1, text: 'Falta de instructor'},
                                    {value: 2, text: 'Falta de sala'},
                                    {value: 3, text: 'Cupo mínimo no cumplido'},
                                    {value: 4, text: 'Curso finalizado exitosamente'},
                                    {value: 0, text: 'Otro'}
                                ]
                            },
                            cascade: function () {
                                if (this.value() == 0) {
                                    bandComm = true;
                                } else {
                                    bandComm = false;
                                    $('comment').removeClass('req');
                                }
                            }
                        }).data('kendoDropDownList');
                    },
                    close: function (e) {
                        if (bandComm && $('#comment').val() == '') {
                            $('#comment').addClass('req');
                            e.preventDefault();
                        }
                    }
                }).data("kendoWindow").open().center();
            } else {
                kendoAlert(resp.res, 'Cursos');
                e.sender.cancelChanges();
            }
        });
    }
}

function changeValCal() {
    if (parseFloat(this.value()) < parseFloat(calif_min)) {
        $(this.element[0]).addClass('reprobado');
    } else {
        $(this.element[0]).removeClass('reprobado');
    }
}

function kendoAlert(message, title) {
    var dialog = $('<div id="windowAlert"></div>');
    var temp = kendo.template($('#dialogAlert').html());
    dialog.html(temp({info: message}));
    dialog.kendoWindow({
        title: title,
        modal: true,
        minWidth: 300,
        deactivate: function () {
            dialog.data('kendoWindow').destroy();
        },
        open: function () {
            dialog.on('click', '#aceptButton', function () {
                dialog.data('kendoWindow').close();
            });
        }
    }).data('kendoWindow').open().center();
}

function kendoAlertTable(data) {
    var dialog = $('<div id="windowAlertTable"></div>');
    var temp = kendo.template($('#dialogUnsuscribed').html());
    dialog.html(temp({res : data}));
    dialog.kendoWindow({
        title: 'Registro de asociados',
        modal: true,
        minWidth: 300,
        deactivate: function () {
            dialog.data('kendoWindow').destroy();
        },
        open: function () {
            dialog.on('click', '#aceptButton', function () {
                dialog.data('kendoWindow').close();
            });
        }
    }).data('kendoWindow').open().center();
}

function checkChanges() {
    var hasChanges = dataSource.hasChanges();
    if (hasChanges === true) {
        return confirm('Aun existen datos sin guardar, si continua los perderá. ¿Desea continuar?');
    }
    return true;
}